﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Markup;
using System.Xml;

namespace ZX_AAA_Workshop
{
  class XmlHlp
  {
    public static string SaveToXmlText<T>(T obj)
    {
      var s = new XmlSerializer(typeof(T));
      using (var writer = new StringWriter())
      {
        s.Serialize(writer, obj);
        return writer.ToString();
      }
    }
    public static T LoadFromXmlText<T>(string xmlText)
    {
      var s = new XmlSerializer(typeof(T));
      using (var reader = new StringReader(xmlText))
        return (T)s.Deserialize(reader);
    }
  }
  class XamlHlp
  {
    public static string SaveToXamlText<T>(T obj)
    {
      var settings = new XmlWriterSettings
      {
        Indent = true,
        NewLineHandling = NewLineHandling.Entitize,
        OmitXmlDeclaration = true,
        //NewLineOnAttributes = true,
      };

      using (var writer = new StringWriter())
      {
        using (var xmlWriter = XmlWriter.Create(writer, settings))
          XamlWriter.Save(obj, xmlWriter);
        return writer.ToString();
      }
    }
  }
  static class ConvertHlp
  {
    public static int? ToInt(string str)
    {
      int result;
      if (int.TryParse(str, out result))
        return result;
      return null;
    }
  }
  static class FileHlp
  {
    public static string MakeValidFileName(string name)
    {
      return MakeValidFileName(name, '_');
    }
    public static string MakeValidFileName(string name, char validChar)
    {
      StringBuilder sb = new StringBuilder(name);
      Array.ForEach(System.IO.Path.GetInvalidFileNameChars(),
        delegate(char c)
        {
          sb.Replace(c, validChar);
        });
      return sb.ToString();
    }

    public static void EnsureDirectory(string dir)
    {
      if (!Directory.Exists(dir))
        Directory.CreateDirectory(dir);
    }
  }
  static class Array<T>
  {
    public static readonly T[] Empty = new T[] { };
  }
  static class StringHlp
  {
    public static bool IsNullOrEmpty(this string str)
    {
      return string.IsNullOrEmpty(str);
    }
  }
}
